package com.zyp.redissentinel.config;

import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisSentinelPool;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

/**
 * @author zhangyanping
 * @version v1
 * @date 2020/11/6 16:52
 */
@Component
public class RedisSentinelConfig {
    private static final String REDIS_MASTER = "master1";

    @Resource
    private RedisTemplate<String, String> stringRedisTemplate;

    @Bean
    private RedisTemplate<String, String> redisTemplate() {
        RedisTemplate<String, String> redis = new RedisTemplate<>();
        redis.setStringSerializer(new StringRedisSerializer());
        redis.afterPropertiesSet();
        return redis;
    }

    @Bean
    private Jedis initJedisSentinel() {
        Set<String> sentinels = new HashSet<>();
        sentinels.add("127.0.0.1:26379");
        sentinels.add("127.0.0.1:26380");
        sentinels.add("127.0.0.1:26381");

        JedisSentinelPool pool = new JedisSentinelPool(REDIS_MASTER, sentinels);
        Jedis jedis = pool.getResource();
        return jedis;
    }
}
